import React, { useState } from 'react';
import { Clock, Search, Filter, CheckCircle, AlertCircle, X, Play, Calendar, FileText, Download, Eye, MoreVertical } from 'lucide-react';
import MenuToggle from '../components/MenuToggle';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Table, TableBody, TableCell, TableHeader, TableRow, TableHead } from '@/components/ui/table';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';

const TaskHistory = ({ toggleSidebar }) => {
  const [searchQuery, setSearchQuery] = useState('');
  const [filterStatus, setFilterStatus] = useState('all');
  const [filterTask, setFilterTask] = useState('all');
  const [selectedHistory, setSelectedHistory] = useState([]);

  // 模拟任务执行历史数据
  const [history] = useState([
    {
      id: 1,
      taskId: 1,
      taskName: '数据备份任务',
      status: 'success',
      startTime: '2024-01-20 02:00:00',
      endTime: '2024-01-20 02:15:32',
      duration: '15分32秒',
      output: '备份完成，共处理 1,234 个文件',
      errorMessage: null,
      triggeredBy: 'schedule'
    },
    {
      id: 2,
      taskId: 2,
      taskName: '文件清理任务',
      status: 'success',
      startTime: '2024-01-19 03:00:00',
      endTime: '2024-01-19 03:08:15',
      duration: '8分15秒',
      output: '清理完成，删除了 456 个临时文件，释放空间 2.3GB',
      errorMessage: null,
      triggeredBy: 'schedule'
    },
    {
      id: 3,
      taskId: 3,
      taskName: '报告生成任务',
      status: 'failed',
      startTime: '2024-01-18 09:00:00',
      endTime: '2024-01-18 09:02:45',
      duration: '2分45秒',
      output: null,
      errorMessage: '数据库连接超时',
      triggeredBy: 'manual'
    },
    {
      id: 4,
      taskId: 4,
      taskName: '系统监控任务',
      status: 'running',
      startTime: '2024-01-20 14:30:00',
      endTime: null,
      duration: '运行中...',
      output: '正在检查系统状态...',
      errorMessage: null,
      triggeredBy: 'schedule'
    },
    {
      id: 5,
      taskName: '邮件发送任务',
      status: 'success',
      startTime: '2024-01-17 08:00:00',
      endTime: '2024-01-17 08:01:23',
      duration: '1分23秒',
      output: '成功发送 25 封邮件',
      errorMessage: null,
      triggeredBy: 'schedule'
    },
    {
      id: 6,
      taskName: '数据同步任务',
      status: 'cancelled',
      startTime: '2024-01-16 10:30:00',
      endTime: '2024-01-16 10:32:10',
      duration: '2分10秒',
      output: '任务被用户取消',
      errorMessage: null,
      triggeredBy: 'manual'
    }
  ]);

  // 获取唯一的任务列表
  const uniqueTasks = [...new Set(history.map(h => h.taskName))];

  const filteredHistory = history.filter(item => {
    const matchesSearch = item.taskName.toLowerCase().includes(searchQuery.toLowerCase()) ||
                         (item.output && item.output.toLowerCase().includes(searchQuery.toLowerCase()));
    const matchesStatus = filterStatus === 'all' || item.status === filterStatus;
    const matchesTask = filterTask === 'all' || item.taskName === filterTask;
    return matchesSearch && matchesStatus && matchesTask;
  });

  const handleHistorySelect = (historyId) => {
    setSelectedHistory(prev => 
      prev.includes(historyId) 
        ? prev.filter(id => id !== historyId)
        : [...prev, historyId]
    );
  };

  const handleSelectAll = () => {
    if (selectedHistory.length === filteredHistory.length) {
      setSelectedHistory([]);
    } else {
      setSelectedHistory(filteredHistory.map(item => item.id));
    }
  };

  const getStatusBadge = (status) => {
    const statusConfig = {
      success: { color: 'bg-green-100 text-green-800', text: '成功', icon: CheckCircle },
      failed: { color: 'bg-red-100 text-red-800', text: '失败', icon: AlertCircle },
      running: { color: 'bg-blue-100 text-blue-800', text: '运行中', icon: Play },
      cancelled: { color: 'bg-gray-100 text-gray-800', text: '已取消', icon: X }
    };
    
    const config = statusConfig[status] || statusConfig.failed;
    const IconComponent = config.icon;
    
    return (
      <Badge className={`${config.color} hover:${config.color}`}>
        <IconComponent className="w-3 h-3 mr-1" />
        {config.text}
      </Badge>
    );
  };

  const getTriggerBadge = (trigger) => {
    return trigger === 'schedule' ? (
      <Badge variant="secondary" className="bg-blue-100 text-blue-800 hover:bg-blue-100">
        <Calendar className="w-3 h-3 mr-1" />
        定时触发
      </Badge>
    ) : (
      <Badge variant="secondary" className="bg-purple-100 text-purple-800 hover:bg-purple-100">
        手动触发
      </Badge>
    );
  };

  const successCount = history.filter(h => h.status === 'success').length;
  const failedCount = history.filter(h => h.status === 'failed').length;
  const runningCount = history.filter(h => h.status === 'running').length;
  const totalExecutions = history.length;

  return (
    <>
      {/* 头部工具栏 */}
      <div className="mt-3">
        <div className="container mx-auto px-4 py-4">
          <div className="flex items-center justify-between">
            {/* 左侧：菜单按钮和标题 */}
            <div className="flex items-center space-x-4">
              <MenuToggle onClick={toggleSidebar} />
              
              <div className="flex items-center space-x-3">
                <div className="w-10 h-10 bg-gradient-to-br from-green-500 to-green-600 rounded-xl flex items-center justify-center">
                  <Clock className="w-6 h-6 text-white" />
                </div>
                <div>
                  <h1 className="text-2xl font-bold text-material-grey-800">
                    执行历史
                  </h1>
                  <p className="text-sm text-material-grey-600">
                    定时任务的执行记录
                  </p>
                </div>
              </div>
            </div>

            {/* 右侧：操作按钮 */}
            <div className="flex items-center space-x-3">
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-material-grey-500" />
                <input
                  type="text"
                  placeholder="搜索执行记录..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="pl-10 pr-4 py-2 w-80 border border-material-grey-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors"
                />
              </div>

              <Select value={filterTask} onValueChange={setFilterTask}>
                <SelectTrigger className="w-48">
                  <SelectValue placeholder="选择任务" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部任务</SelectItem>
                  {uniqueTasks.map(task => (
                    <SelectItem key={task} value={task}>
                      {task}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>

              <Select value={filterStatus} onValueChange={setFilterStatus}>
                <SelectTrigger className="w-32">
                  <Filter className="w-4 h-4 mr-2" />
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部状态</SelectItem>
                  <SelectItem value="success">成功</SelectItem>
                  <SelectItem value="failed">失败</SelectItem>
                  <SelectItem value="running">运行中</SelectItem>
                  <SelectItem value="cancelled">已取消</SelectItem>
                </SelectContent>
              </Select>

              <Button variant="outline">
                <Download className="w-4 h-4 mr-2" />
                导出记录
              </Button>
            </div>
          </div>
        </div>
      </div>

      {/* 主内容区域 */}
      <div className="flex-1 container mx-auto px-4 py-6">
        {/* 统计卡片 */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-material-grey-600">总执行次数</p>
                  <p className="text-2xl font-bold text-material-grey-900">{totalExecutions}</p>
                </div>
                <div className="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                  <Clock className="w-6 h-6 text-blue-600" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-material-grey-600">成功执行</p>
                  <p className="text-2xl font-bold text-green-600">{successCount}</p>
                </div>
                <div className="w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center">
                  <CheckCircle className="w-6 h-6 text-green-600" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-material-grey-600">执行失败</p>
                  <p className="text-2xl font-bold text-red-600">{failedCount}</p>
                </div>
                <div className="w-12 h-12 bg-red-100 rounded-lg flex items-center justify-center">
                  <AlertCircle className="w-6 h-6 text-red-600" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-material-grey-600">成功率</p>
                  <p className="text-2xl font-bold text-purple-600">
                    {totalExecutions > 0 ? Math.round((successCount / totalExecutions) * 100) : 0}%
                  </p>
                </div>
                <div className="w-12 h-12 bg-purple-100 rounded-lg flex items-center justify-center">
                  <FileText className="w-6 h-6 text-purple-600" />
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* 执行历史列表 */}
        <Card>
          <CardContent className="p-0">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-12">
                    <input
                      type="checkbox"
                      checked={selectedHistory.length === filteredHistory.length && filteredHistory.length > 0}
                      onChange={handleSelectAll}
                      className="w-4 h-4 text-primary border-material-grey-300 rounded focus:ring-primary/50"
                    />
                  </TableHead>
                  <TableHead>任务信息</TableHead>
                  <TableHead>状态</TableHead>
                  <TableHead>执行时间</TableHead>
                  <TableHead>持续时间</TableHead>
                  <TableHead>触发方式</TableHead>
                  <TableHead className="text-right">操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredHistory.map((item) => (
                  <TableRow key={item.id}>
                    <TableCell>
                      <input
                        type="checkbox"
                        checked={selectedHistory.includes(item.id)}
                        onChange={() => handleHistorySelect(item.id)}
                        className="w-4 h-4 text-primary border-material-grey-300 rounded focus:ring-primary/50"
                      />
                    </TableCell>
                    <TableCell>
                      <div className="space-y-1">
                        <p className="font-medium text-material-grey-900">{item.taskName}</p>
                        <p className="text-sm text-material-grey-500">ID: {item.id}</p>
                        {item.output && (
                          <p className="text-xs text-material-grey-600 max-w-md truncate">
                            {item.output}
                          </p>
                        )}
                        {item.errorMessage && (
                          <p className="text-xs text-red-600 max-w-md truncate">
                            错误: {item.errorMessage}
                          </p>
                        )}
                      </div>
                    </TableCell>
                    <TableCell>
                      {getStatusBadge(item.status)}
                    </TableCell>
                    <TableCell>
                      <div className="text-sm">
                        <div className="text-material-grey-900">{item.startTime}</div>
                        {item.endTime && (
                          <div className="text-material-grey-500">至 {item.endTime}</div>
                        )}
                      </div>
                    </TableCell>
                    <TableCell>
                      <span className="text-sm text-material-grey-700">{item.duration}</span>
                    </TableCell>
                    <TableCell>
                      {getTriggerBadge(item.triggeredBy)}
                    </TableCell>
                    <TableCell className="text-right">
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <Button variant="ghost" size="icon">
                            <MoreVertical className="w-4 h-4" />
                          </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end">
                          <DropdownMenuItem>
                            <Eye className="w-4 h-4 mr-2" />
                            查看详情
                          </DropdownMenuItem>
                          <DropdownMenuItem>
                            <Download className="w-4 h-4 mr-2" />
                            下载日志
                          </DropdownMenuItem>
                          {item.status === 'failed' && (
                            <DropdownMenuItem>
                              <Play className="w-4 h-4 mr-2" />
                              重新执行
                            </DropdownMenuItem>
                          )}
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>

            {filteredHistory.length === 0 && (
              <div className="text-center py-12">
                <div className="w-24 h-24 mx-auto mb-4 bg-material-grey-200 rounded-full flex items-center justify-center">
                  <Clock className="w-8 h-8 text-material-grey-500" />
                </div>
                <h3 className="text-lg font-medium text-material-grey-700 mb-2">
                  {searchQuery ? '未找到匹配的执行记录' : '暂无执行历史'}
                </h3>
                <p className="text-material-grey-500">
                  {searchQuery ? '尝试使用不同的关键词搜索' : '任务执行后，记录将显示在这里'}
                </p>
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </>
  );
};

export default TaskHistory;
